<template>
  <div class="card-body">
    <el-table border height="300" :data="listData">
      <el-table-column prop="country_area_name" label="国家区域">
        <template #default="{ row }">
          {{ row.country_area_name }}
          <span class="text-red-500" v-if="!row.status">禁用</span>
        </template>
      </el-table-column>
      <el-table-column prop="country_list_text" label="国家">
        <template #default="{ row }">
          <VText :value="row.country_list_text?.join('、')"></VText>
        </template>
      </el-table-column>
      <el-table-column prop="gross_weight_g" label="产品重量">
        <template #default="{ row }">
          <div>{{ row.gross_weight_g }} g</div>
          <div></div>
        </template>
      </el-table-column>
      <el-table-column prop="volume" label="产品体积">
        <template #default="{ row }">
          <div>{{ row.volume }} cm³</div>
          <div></div>
        </template>
      </el-table-column>
      <el-table-column prop="customs_declaration_price" label="报关价格">
        <template #default="{ row }">
          <div>{{ row.customs_declaration_price }} USD</div>
          <div>{{ row.customs_declaration_price_cny }} CNY</div>
        </template>
      </el-table-column>
      <el-table-column prop="operation_user_ids_text" label="头程空运参考">
        <template #header>
          <div>头程空运参考</div>
          <div>
            <el-button
              type="primary"
              link
              @click="handleAirTransport"
              :disabled="disabled"
              >设置</el-button
            >
          </div>
        </template>
        <template #default="{ row }">
          {{ row.air_transport_price }} CNY/kg
          <div></div>
        </template>
      </el-table-column>
      <el-table-column prop="operation_user_ids_text" label="头程海运参考" width="140">
        <template #header>
          <div>头程海运参考</div>
          <div>
            <el-button
              type="primary"
              link
              @click="handleSeaTransport"
              :disabled="disabled"
              >设置</el-button
            >
          </div>
        </template>
        <template #default="{ row }">
          <div>{{ row.sea_transport_bulk }} m³/{{ row.sea_transport_price }} CNY</div>
        </template>
      </el-table-column>
      <el-table-column prop="import_duty_radio" label="进口税费比例参考">
        <template #default="{ row }">
          <div>{{ row.import_duty_radio }} %</div>
        </template>
      </el-table-column>
      <el-table-column prop="single_freight" label="单个运费（CNY）">
        <template #header="{ row }">
          <div class="flex items-center">
            单个运费（CNY）
            <el-tooltip placement="top">
              <template #content
                >说明：1、头程空运参考/头程海云参考/进口税费比例参考：可在基础管理-产品头程运费参考管理中设置；<br />
                2、只有未发过头程的SKU，运费从此处维护的单价中获取运费成本；<br />
                3、计算公式：<br />
                &nbsp;&nbsp;3.1、单个海运运费：（参考价格/立方/1000000）*产品体积<br />
                &nbsp;&nbsp;3.2、单个空运运费：（参考价格/1000）*产品重量<br />
                &nbsp;&nbsp;3.3、单个税费：报关价*进口税费比例<br />
                4、产品重量：取SKU毛重<br />
                5、产品体积：取SKU包装尺寸<br />
                6、报关价：取SKU绑定默认供应商的报关价格</template
              >
              <svg-icon icon-class="QuestionFilled"></svg-icon>
            </el-tooltip>
          </div>
        </template>
        <template #default="{ row }">
          <div>{{ row.single_freight || 0 }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="single_tax_fee" label="单个税费（CNY）">
        <template #default="{ row }">
          <div>{{ row.single_tax_fee || 0 }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="120">
        <template #default="{ row, $index }">
          <el-button
            link
            type="primary"
            @click="handleEdit(row, $index)"
            :disabled="disabled"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <ComModal ref="comModalRef" :listData="listData" @updateForm="updateForm"></ComModal>
  </div>
</template>

<script setup lang="jsx" name="head-freight">
import ComModal from "./ComModal.vue";
import { nextTick } from "vue";
let handleType = reactive(inject("handleType"));
let base_head_freight_list = reactive(inject("base_head_freight_list"));
const props = defineProps({
  modelValue: {
    type: [Array, String],
    default: () => {
      return [];
    },
  },
  info: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const { info } = toRefs(props);

const disabled = computed(() => {
  return (
    handleType.value == "view" ||
    (handleType.value == "edit" &&
      !(window.BTN_AUTH || []).includes("/goods/task/product/head-freight"))
  );
});
const emit = defineEmits(["update:modelValue"]);

const listData = computed({
  get: () => {
    return props.modelValue;
  },
  set: (val) => {
    emit("update:modelValue", val);
  },
});

const comModalRef = ref();
const currentIndex = ref("");

const handleEdit = (row, rowIndex) => {
  nextTick(() => {
    currentIndex.value = rowIndex;
    comModalRef.value.open({
      ...row,
      sku: info.value.sku,
    });
  });
};

const updateForm = (row) => {
  nextTick(() => {
    listData.value.splice(currentIndex.value, 1, row);
  });
};

const init = async () => {
  const item = info.value.goods_sku_supplier.find((i) => i.default_supplier);
  const customs_declaration_price = item?.goods_sku_customs?.declare_price_usd || 0;
  const volume = (
    Number(info.value.packing_size_cm?.width || 0) *
    Number(info.value.packing_size_cm?.length || 0) *
    Number(info.value.packing_size_cm?.height || 0)
  ).toFixed(2);
  if (!listData.value?.length) {
    const tableData = base_head_freight_list.value
      .map((item) => {
        item.gross_weight_g = info.value.gross_weight_g || 0;
        item.volume = volume;
        item.customs_declaration_price = customs_declaration_price || 0;
        item.customs_declaration_price_cny = (
          Number(customs_declaration_price || 0) * info.value.exchange_rate
        ).toFixed(2);

        return item;
      })
      .filter((j) => j.status == 1);
    listData.value = tableData;
  } else {
    const listDataMap = {};
    listData.value.forEach((item) => {
      listDataMap[item.base_head_freight_id] = {
        ...item,
        single_freight: item.single_freight,
        single_tax_fee: item.single_tax_fee,
        id: item.id,
      };
    });
    const tableData = base_head_freight_list.value
      .map((item) => {
        const newItem = {
          ...item,
          gross_weight_g: info.value.gross_weight_g || 0, // 保证了undefined值的情况有默认值
          volume: volume,
          customs_declaration_price: customs_declaration_price || 0, // 同上
          customs_declaration_price_cny: (
            Number(customs_declaration_price || 0) * info.value.exchange_rate
          ).toFixed(2),
        };
        const find = listDataMap[item.base_head_freight_id];
        if (find) {
          newItem.single_freight = find?.single_freight;
          newItem.single_tax_fee = find?.single_tax_fee;
          newItem.id = find?.id;
        }
        return newItem;
      })
      .filter((j) => j.status == 1 || j.id);
    listData.value = tableData;
  }
};

// 设置空运费用
const handleAirTransport = () => {
  listData.value.forEach((item) => {
    item.single_freight = Number(
      (item.air_transport_price / 1000) * item.gross_weight_g
    ).toFixed(2);
    item.single_tax_fee =
      Number(item.customs_declaration_price_cny) > 0
        ? Number(
            item.customs_declaration_price_cny * (item.import_duty_radio / 100)
          ).toFixed(2)
        : 0;
  });
};

// 设置海运费用
const handleSeaTransport = () => {
  listData.value.forEach((item) => {
    item.single_freight = Number(
      (item.sea_transport_price / item.sea_transport_bulk / 1000000) * item.volume
    ).toFixed(2);
    item.single_tax_fee =
      Number(item.customs_declaration_price_cny) > 0
        ? Number(
            item.customs_declaration_price_cny * (item.import_duty_radio / 100)
          ).toFixed(2)
        : 0;
  });
};

onMounted(async () => {
  await init();
});

defineExpose({ init });
</script>

<style lang="scss" scoped></style>
